package com.nowcoder.community.controller;

import com.nowcoder.community.annotation.RestLoginRequire;
import com.nowcoder.community.controller.exception.PageNotFoundException;
import com.nowcoder.community.entity.Comment;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Page;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.CommentService;
import com.nowcoder.community.service.DiscussPostService;
import com.nowcoder.community.util.Constants;
import com.nowcoder.community.util.HostHolder;
import com.nowcoder.community.util.JsonBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Slf4j
@Controller
@RequestMapping("discuss")
public class DiscussPostController {
    @Autowired
    DiscussPostService discussPostService;

    @Autowired
    CommentService commentService;

    @Autowired
    HostHolder hostHolder;

    @RestLoginRequire
    @ResponseBody
    @PostMapping("publish")
    public JsonBody addPost(String title, String content) {
        User user = hostHolder.getUser();
        DiscussPost post = new DiscussPost();
        post.setUserId(user.getId());
        post.setTitle(title);
        post.setContent(content);
        return discussPostService.addPost(post);
    }

    @GetMapping("detail/{discussPostId}")
    public ModelAndView getPostDetail(@PathVariable int discussPostId, Page commentPage) throws PageNotFoundException {
        log.debug("用户访问帖子{}的详细页面.", discussPostId);
        commentPage.setLimit(5);
        ModelAndView ret = discussPostService.getPostDetailPage(discussPostId, commentPage);
        if (commentPage.getRows() > 0) {
            List<Comment> comments = commentService.findCommentsByEntity(discussPostId, Constants.ENTITY_TYPE_POST, commentPage);
            ret.addObject("comments", comments);
        }
        return ret;
    }
}